function padLeftZero(str) {
  return ("00" + str).substr(str.length)
}

export function dateFormat(date) {
  return date.replace("T", " ")
}

export function formatDate(timestamp, fmt) {
  const date = new Date(timestamp)
  if (!fmt) {
    fmt = "yyyy-MM-dd hh:mm:ss"
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
  }
  const o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ""
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
    }
  }
  return fmt
}

export function friendlyDate(date) {
  const formats = {
    "year": "%n% 年前",
    "month": "%n% 月前",
    "day": "%n% 天前",
    "hour": "%n% 小时前",
    "minute": "%n% 分钟前",
    "second": "%n% 秒前"
  }
  const timestamp = Date.parse(dateFormat(date))
  const now = Date.now()
  let seconds = Math.floor((now - timestamp) / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)
  const months = Math.floor(days / 30)
  const years = Math.floor(months / 12)

  let diffType = ""
  let diffValue = 0
  if (years > 0) {
    diffType = "year"
    diffValue = years
    return formatDate(timestamp)
  } else {
    if (months > 0) {
      diffType = "month"
      diffValue = months
    } else {
      if (days > 0) {
        diffType = "day"
        diffValue = days
      } else {
        if (hours > 0) {
          diffType = "hour"
          diffValue = hours
        } else {
          if (minutes > 0) {
            diffType = "minute"
            diffValue = minutes
          } else {
            diffType = "second"
            diffValue = seconds === 0 ? seconds = 1 : seconds
          }
        }
      }
    }
  }
  return formats[diffType].replace("%n%", diffValue)
}
